#include "mainwindow.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QFileDialog>
#include <QMessageBox>
#include <QStatusBar>
#include <QStyle>
#include <QResizeEvent>
#include <opencv2/opencv.hpp>
#include <QPushButton>
#include <QLabel>
#include <QSlider>
#include <QStandardPaths>
#include <QDebug>
#include <QDateTime>
#include <QProgressDialog>
#include <QThread>
#include <QDir>
#include <QDesktopServices>
#include <QComboBox>
#include <QGroupBox>
#include <QSerialPortInfo>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent) {
    initUI();

    // 连接信号
    connect(btnOpenCamera, &QPushButton::toggled, this, [this]() {
        detectionSettings.isCameraOn = !detectionSettings.isCameraOn;
    });
    connect(btnDetect, &QPushButton::toggled, this, [this]() {
        detectionSettings.isDetectOn = !detectionSettings.isDetectOn;
    });
    //connect(btnReset, &QPushButton::clicked, this, &MainWindow::reset);
    connect(btnPassenger, &QPushButton::toggled, this, [this]() {
        detectionSettings.isDetectPassenerOn = !detectionSettings.isDetectPassenerOn;
    });
    connect(btnSpark, &QPushButton::toggled, this, [this]() {
        detectionSettings.isDetectSpakerOn = !detectionSettings.isDetectSpakerOn;
    });
    connect(btnIntruder, &QPushButton::toggled, this, [this]() {
        detectionSettings.isDetectIntruderOn = !detectionSettings.isDetectIntruderOn;
    });

    // 连接串口按钮信号
    connect(btnScanPort, &QPushButton::clicked, this, &MainWindow::scanSerialPorts);
    connect(btnOpenPort, &QPushButton::toggled, this, &MainWindow::toggleOpenSerial);

    imageWorkerThread = new QThread(this);
    imageworker = new imageWorker(detectionSettings,resultSettings);
    imageworker->moveToThread(imageWorkerThread);

    // 当线程启动时，开始循环采集
    connect(imageWorkerThread, &QThread::started, imageworker, &imageWorker::processImage);

    // 图像就绪时，更新UI
    connect(imageworker, &imageWorker::frameReady, this, [=](const QImage &img){
        displayImage(img);  // 已有的显示函数
    });

    // 退出时清理
    connect(this, &MainWindow::destroyed, imageWorkerThread, &QThread::quit);
    connect(imageWorkerThread, &QThread::finished, imageworker, &QObject::deleteLater);

    // 启动摄像头和线程
    imageworker->startCapture(0);  // 默认摄像头0
    imageWorkerThread->start();

    // 创建串口线程
    uartWorkerThread = new QThread(this);
    uartworker = new uartWorker(resultSettings);
    uartworker->moveToThread(uartWorkerThread);

    // 串口数据回到 UI
    connect(uartworker, &uartWorker::dataReceived, this, [=](const QByteArray &data){
        // 把字节数据转成16进制显示，例如 "01 02 03"
        QString hexStr = data.toHex(' ').toUpper();
        statusLabel->setText("回传数据: " + hexStr);
        statusLabel->setStyleSheet("background-color: #4CAF50; color: white; padding: 5px;");
    });


    connect(imageworker, &imageWorker::frameReady, uartworker, &uartWorker::processUart);

    // 打开串口
    connect(this, &MainWindow::openSerial, uartworker, &uartWorker::openSerial);
    // 关闭串口
    connect(this, &MainWindow::closeSerial, uartworker, &uartWorker::closeSerial);
    // 发送数据
    connect(this, &MainWindow::sendData, uartworker, &uartWorker::writeData);

    uartWorkerThread->start();
}

MainWindow::~MainWindow() {}

void MainWindow::initUI() {
    // 创建中央部件
    centralWidget = new QWidget(this);
    setCentralWidget(centralWidget);

    // 主布局
    QHBoxLayout *mainLayout = new QHBoxLayout(centralWidget);

    // 左侧控制面板
    QWidget *controlPanel = new QWidget();
    controlPanel->setFixedWidth(250);
    QVBoxLayout *controlLayout = new QVBoxLayout(controlPanel);
    controlLayout->setAlignment(Qt::AlignTop);

    // 创建按钮
    btnOpenCamera = new QPushButton("打开相机");
    btnDetect = new QPushButton("开始检测");
    btnReset = new QPushButton("重置");
    // 检测功能开关
    btnPassenger = new QPushButton("客流量检测");
    btnSpark = new QPushButton("着火检测");
    btnIntruder = new QPushButton("入侵检测");

    // 设置为可切换按钮
    btnOpenCamera->setCheckable(true);
    btnDetect->setCheckable(true);  
    btnPassenger->setCheckable(true);
    btnSpark->setCheckable(true);
    btnIntruder->setCheckable(true);

    // 默认状态
    btnOpenCamera->setChecked(false);
    btnDetect->setChecked(false);
    btnPassenger->setChecked(false);
    btnSpark->setChecked(false);
    btnIntruder->setChecked(false);

    // 设置按钮样式
    QString buttonStyle = "QPushButton {"
                          "background-color: #FF5722;"
                          "color: white;"
                          "font-weight: bold;"
                          "border: none;"
                          "padding: 10px;"
                          "border-radius: 5px;"
                          "margin: 5px;"
                          "}"
                          "QPushButton:hover {"
                          "background-color: #E64A19;"
                          "}"
                          "QPushButton:disabled {"
                          "background-color: #BDBDBD;"
                          "}";
    // 开关按钮样式
    QString toggleStyle =
        "QPushButton {"
        "   border: none;"
        "   border-radius: 5px;"
        "   font-weight: bold;"
        "   color: white;"
        "   padding: 10px;"
        "   margin: 5px;"
        "}"
        "QPushButton:checked {"
        "   background-color: #FF5722;"
        "}"
        "QPushButton:!checked {"
        "   background-color: #BDBDBD;"
        "}";

    btnOpenCamera->setStyleSheet(toggleStyle);
    btnDetect->setStyleSheet(toggleStyle);
    btnReset->setStyleSheet(buttonStyle);
    btnPassenger->setStyleSheet(toggleStyle);
    btnSpark->setStyleSheet(toggleStyle);
    btnIntruder->setStyleSheet(toggleStyle);

    // 设置按钮大小
    QSize buttonSize(220, 50);
    btnOpenCamera->setFixedSize(buttonSize);
    btnDetect->setFixedSize(buttonSize);
    btnReset->setFixedSize(buttonSize);
    btnPassenger->setFixedSize(buttonSize);
    btnSpark->setFixedSize(buttonSize);
    btnIntruder->setFixedSize(buttonSize);

    btnPassenger->setStyleSheet(toggleStyle);
    btnSpark->setStyleSheet(toggleStyle);
    btnIntruder->setStyleSheet(toggleStyle);

    // 添加分割线
    QFrame *line = new QFrame();
    line->setFrameShape(QFrame::HLine);
    line->setFrameShadow(QFrame::Sunken);
    line->setStyleSheet("color: #BDBDBD; margin: 10px 0;");

    // 串口控制组
    QGroupBox *serialGroup = new QGroupBox("串口设置");
    serialGroup->setStyleSheet("QGroupBox { font-weight: bold; border: 1px solid gray; border-radius: 5px; margin-top: 10px; padding-top: 10px; } QGroupBox::title { subcontrol-origin: margin; left: 10px; }");
    QVBoxLayout *serialLayout = new QVBoxLayout(serialGroup);

    // 串口选择
    QHBoxLayout *portLayout = new QHBoxLayout();
    QLabel *portLabel = new QLabel("端口:");
    comboPort = new QComboBox();
    comboPort->setFixedHeight(30);
    btnScanPort = new QPushButton("扫描");
    btnScanPort->setFixedSize(60, 30);
    btnScanPort->setStyleSheet(buttonStyle);
    portLayout->addWidget(portLabel);
    portLayout->addWidget(comboPort);
    portLayout->addWidget(btnScanPort);

    // 波特率选择
    QHBoxLayout *baudLayout = new QHBoxLayout();
    QLabel *baudLabel = new QLabel("波特率:");
    comboBaud = new QComboBox();
    comboBaud->setFixedHeight(30);
    comboBaud->addItems({"2400", "9600", "19200", "38400", "57600", "115200"});
    comboBaud->setCurrentText("2400"); // 默认波特率
    baudLayout->addWidget(baudLabel);
    baudLayout->addWidget(comboBaud);

    // 打开串口按钮
    btnOpenPort = new QPushButton("打开串口");
    btnOpenPort->setCheckable(true);
    btnOpenPort->setFixedSize(215, 50);
    btnOpenPort->setStyleSheet(toggleStyle);

    serialLayout->addLayout(portLayout);
    serialLayout->addLayout(baudLayout);
    serialLayout->addWidget(btnOpenPort);

    QFont ft;
    ft.setPointSize(9);

    // 状态标签
    statusLabel = new QLabel("就绪");
    statusLabel->setAlignment(Qt::AlignCenter);
    statusLabel->setStyleSheet("background-color: #4CAF50; color: white; padding: 5px;");
    statusLabel->setFont(ft);


    // 添加到控制面板
    controlLayout->addWidget(btnOpenCamera);
    controlLayout->addWidget(btnDetect);

    controlLayout->addSpacing(10);
    controlLayout->addWidget(line);
    controlLayout->addSpacing(10);

    // 添加到控制面板
    controlLayout->addWidget(btnSpark);
    controlLayout->addWidget(btnIntruder);
    controlLayout->addWidget(btnPassenger);

    controlLayout->addSpacing(10);

    // 添加串口控制组
    controlLayout->addWidget(serialGroup);

    //controlLayout->addWidget(btnReset);

    controlLayout->addStretch();
    controlLayout->addWidget(statusLabel);

    // 添加说明标签
    QLabel *infoLabel = new QLabel(
        "使用说明：\n"
        "1. 点击'打开相机'打开相机并显示图像\n"
        "2. 点击'开始检测'识别并显示检测图片\n"
        "3. 点击'着火检测'用红色方框标识火焰\n"
        "4. 点击'入侵检测'蓝色方框标识入侵者\n"
        "5. 点击'客流量检测'绿色方框标识顾客"
        );
    infoLabel->setStyleSheet("background-color: #E3F2FD; padding: 10px; border-radius: 5px;");
    controlLayout->addWidget(infoLabel);

    // 右侧图像显示区域
    QWidget *imagePanel = new QWidget();
    QVBoxLayout *imageLayout = new QVBoxLayout(imagePanel);

    // 图像标签
    imageLabel = new QLabel();
    imageLabel->setAlignment(Qt::AlignCenter);
    imageLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    imageLabel->setStyleSheet("background-color: #333; border: 1px solid #555;");
    imageLabel->setText("等待开启相机...");
    imageLabel->setStyleSheet("color: #888; font-style: italic;");

    // 添加标题
    QLabel *imageTitle = new QLabel("图像显示区域");
    imageTitle->setAlignment(Qt::AlignCenter);
    imageTitle->setStyleSheet("font-weight: bold; font-size: 16px; margin-bottom: 10px; color: #FF5722;");

    imageLayout->addWidget(imageTitle);
    imageLayout->addWidget(imageLabel);

    // 添加控件到主布局
    mainLayout->addWidget(controlPanel);
    mainLayout->addWidget(imagePanel, 1); // 图像区域占据剩余空间

    // 设置窗口属性
    setWindowTitle("商店监控系统");
    resize(1200, 800);

    // 初始状态
    reset();
}

void MainWindow::reset() {
    detectionSettings.isCameraOn = false;
    detectionSettings.isDetectOn = false;
    detectionSettings.isDetectSpakerOn = false;
    detectionSettings.isDetectPassenerOn = false;
    detectionSettings.isDetectIntruderOn = false;

    btnOpenCamera->setChecked(false);
    btnDetect->setChecked(false);
    btnPassenger->setChecked(false);
    btnSpark->setChecked(false);
    btnIntruder->setChecked(false);

    imageLabel->clear();
    statusLabel->clear();

    imageLabel->setText("等待开启相机...");
    imageLabel->setStyleSheet("color: #888; font-style: italic;");
    statusLabel->setText("等待检测...");
    statusLabel->setStyleSheet("background-color: #4CAF50; color: white; padding: 5px;");
}

void MainWindow::displayImage(const QImage &image) {
    if (image.isNull()) return;

    QPixmap pixmap = QPixmap::fromImage(image);
    pixmap = pixmap.scaled(imageLabel->width(), imageLabel->height(),
                           Qt::KeepAspectRatio, Qt::SmoothTransformation);
    imageLabel->setPixmap(pixmap);
}

void MainWindow::scanSerialPorts() {
    comboPort->clear();
    QList<QSerialPortInfo> ports = QSerialPortInfo::availablePorts();
    // 按数字顺序排序（保留"COM"前缀显示）
    std::sort(ports.begin(), ports.end(), [](const QSerialPortInfo &a, const QSerialPortInfo &b) {
        // 提取端口号部分（去掉"COM"前缀，只用于比较）
        int na = a.portName().mid(3).toInt();
        int nb = b.portName().mid(3).toInt();
        return na < nb;
    });

    for (const QSerialPortInfo &port : ports) {
        comboPort->addItem(port.portName(), port.systemLocation());
    }

    if (ports.isEmpty()) {
        comboPort->addItem("无可用串口");
        btnOpenPort->setEnabled(false);
    } else {
        btnOpenPort->setEnabled(true);
    }
}

void MainWindow::toggleOpenSerial(bool checked) {
    if (checked) {
        // 打开串口
        QString portName = comboPort->currentText();
        int baudRate = comboBaud->currentText().toInt();

        if (portName.isEmpty() || portName == "无可用串口") {
            btnOpenPort->setChecked(false);
            QMessageBox::warning(this, "错误", "没有可用的串口");
            return;
        }

        emit openSerial(portName, baudRate);
        btnOpenPort->setText("关闭串口");
        statusLabel->setText("已打开串口: " + portName);
    } else {
        // 关闭串口
        emit closeSerial();
        btnOpenPort->setText("打开串口");
        statusLabel->setText("串口已关闭");
    }
}
